package com.chen.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chen.model.entity.user.UserInfo;
import com.chen.model.vo.common.Result;
import com.chen.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author cgj
 * @date 4/21/25 7:45 PM
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    // spring 提供的路径工具类
     private AntPathMatcher antPathMatcher=new AntPathMatcher();
     @Autowired
     private RedisTemplate<String,String> redisTemplate;


    /**
     * 对包含 auth的路径进行token的过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 例如/api/user/userInfo/auth/findUserBrowseHistoryPage/1/10
        String path = request.getURI().getPath();
        //  带有auth就判断是否有token
        if(antPathMatcher.match("/**/auth/**",path)){

            //根据token 获取用户信息
            UserInfo userInfo=getUserInfo(request);
            //为空直接拦截
            if(userInfo==null){
                return out(exchange.getResponse(), ResultCodeEnum.LOGIN_AUTH);
            }

        }
        return chain.filter(exchange); //放行
    }
    /**
     *    封装响应数据的方法
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        String resultJson = JSON.toJSONString(result);
        DataBuffer buffer = response.bufferFactory().wrap(resultJson.getBytes(StandardCharsets.UTF_8));
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    private UserInfo getUserInfo(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("token"); //getFirst是只要一个
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        // 查不到直接返回
        if(StringUtils.isEmpty(userJson)){
             return null;
        }
        //转换为user返回
        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        return  userInfo;
    }

    /**
     * 排序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
